package com.xjr.websocket.config;/*
 *@date 2019/9/30 0030
 */

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/websocket/{uname}")
public class WebsocketConfig {
    private static Logger logger= LoggerFactory.getLogger(WebsocketConfig.class);

    private static int countNum=0;

    private static CopyOnWriteArraySet<WebsocketConfig> configs=new CopyOnWriteArraySet<WebsocketConfig>();

    private Session session;

    private  String uname="";

    @OnOpen
    public void onOpen(Session session, @PathParam("uname")String uname){
        this.uname=uname;
        this.session=session;
        configs.add(this);
        addOnlineCount();
    }
    public static synchronized int getOnlineCount() {
        return countNum;
    }

    public static synchronized void addOnlineCount() {
        WebsocketConfig.countNum++;
    }

    public static synchronized void subOnlineCount() {
        WebsocketConfig.countNum--;
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        configs.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        logger.info("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    @OnMessage
    public void onMessage(Session session,String message){
        logger.info("收到来自窗口"+uname+"的信息:"+message);
        //群发消息
        for (WebsocketConfig item : configs) {
            try {
                item.sendMessage("<span style='margin:0 50px 0 50px;float:left'>"+uname+":"+message.replace("<p>","").replace("</p>","")+"</span><br>");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
